package com.cndw.kungfu.business.gm;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.cndw.kungfu.comm.LocalCommand;
import com.cndw.kungfu.domain.GoodsMode;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.Task;
import com.cndw.kungfu.domain.TaskMode;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.NumberProcesser;
import com.cndw.kungfu.ext.StringProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.goods.PlayerBoxs;
import com.cndw.kungfu.model.task.TaskManager;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.annotation.UnAuth;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

/**
 * 任务处理接口
 * 
 * @author fantadust [9677889@qq.com]
 * @date 2011-6-8 上午11:14:54
 */
@Controller
public class BusinessTask {

	@Autowired
	private TaskManager taskManager;

	@UnAuth
	@LocalCommand
	public ResponseMessage accept(Session session, String sign, int taskId, String accountName) {

		long playerId = Context.getPlayerServer().getPlayerIdByAccount(accountName);
		Player player = Context.getPlayerServer().getByPlayerId(playerId);

		if (player == null) {
			return null;// 正在做
		}

		taskManager.cancelTask(playerId, taskId);

		TaskMode taskMode = taskManager.getModeById(taskId);
		if (taskMode == null) {
			return null;
		}
		int[] giveItem = null;
		if (taskMode.getGiveItem() != null) {
			giveItem = StringProcesser.toIntArray(taskMode.getGiveItem());
			if (giveItem != null) {
				GoodsMode goodsMode = Context.getGoodsServer().getModeById(giveItem[0]);
				if (goodsMode != null && !goodsMode.isTaskItem()) {
					int block = NumberProcesser.ceil(giveItem[1], goodsMode.getMaxStack());
					PlayerBoxs playerBoxs = player.getPlayerBoxs();
					if (!playerBoxs.checkBlack(block)) {
						return ResponseMessage.errMsg(LanguageLib.get("comm.player.boxmin", block));
					}
				}
			}
		}

		Task task = taskManager.acceptTask(playerId, taskId);
		if (task == null) {
			return ResponseMessage.errMsg(LanguageLib.get("comm.err.sys"));
		}

		if (giveItem != null) {
			Context.getGoodsServer().giveGoodsBing(playerId, giveItem[0], giveItem[1], 1);
		}
		Map<String, Object> map = new HashMap<String, Object>();

		autoRadioTask(playerId);

		map.put("suc", true);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 自动广播我的任务
	 * 
	 * @param session
	 * @param sceneId
	 */
	private void autoRadioTask(long playerId) {
		Context.getTaskServer().autoRaidioTask(playerId, 1);
	}
}
